package com.itheima.protocol.zkClient;

import org.I0Itec.zkclient.IZkChildListener;
import org.I0Itec.zkclient.IZkDataListener;
import org.I0Itec.zkclient.ZkClient;

import java.util.List;
import java.util.concurrent.TimeUnit;

public class ZkClientApiOperatorDemo {

    private final static String CONNECTIONSTRING="192.168.56.102:2181";
    private final static int SESSIONTIMEOUT = 5000;

    public static ZkClient getInstance(){
        return new ZkClient(CONNECTIONSTRING, SESSIONTIMEOUT);
    }

    public static void main(String[] args) {

        ZkClient zkClient = getInstance();

        //创建临时节点
        zkClient.createEphemeral("/ephemeral");
        System.out.println("create ephemeral node success");

        //创建持久化节点
        zkClient.createPersistent("/persistent/p-1",true);
        System.out.println("create persistent node success");

        //删除一个递归节点
        if(zkClient.exists("/node1")) {
            zkClient.deleteRecursive("/node1");
            System.out.println("delete node success");
        }

        //获取子节点
        List<String> childrenNodes = zkClient.getChildren("/persistent");
        System.out.println(childrenNodes);

        //watcher(子节点数据改变事件订阅)
        zkClient.subscribeDataChanges("/persistent",new IZkDataListener(){

            @Override
            public void handleDataChange(String dataPath, Object data) throws Exception {

                System.out.println("节点名称：" + dataPath + "--> 节点修改后的值：" + data);
            }

            @Override
            public void handleDataDeleted(String dataPath) throws Exception {

            }
        });

        zkClient.writeData("/persistent","persistent");
        try {
            TimeUnit.SECONDS.sleep(1);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }


        zkClient.subscribeChildChanges("/persistent", new IZkChildListener() {
            @Override
            public void handleChildChange(String s, List<String> list) throws Exception {
                System.out.println("子节点发生变化");
            }
        });

    }
}

